package com.sky.category.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.C;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.category.service.ICategoryService;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.result.PageResult;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-18
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/{userType}/category")
@Api(tags = "分类相关接口")
@Slf4j
public class CategoryController {

    private final ICategoryService categoryService;

    @ApiOperation("修改分类")
    @PutMapping
    public Result<String> update(@RequestBody CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        boolean result = categoryService.updateById(category);
        if (!result) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @ApiOperation("根据类型查询分类")
    @GetMapping("/list")
    public Result<List<Category>> list(Integer type) {
        List<Category> list = categoryService.lambdaQuery()
                .eq(type!=null, Category::getType, type)
                .list();
        return Result.success(list);
    }
    @GetMapping("/page")
    public Result<PageResult> page(CategoryPageQueryDTO categoryPageQueryDTO){
        Page<Category> page=categoryPageQueryDTO.toPage();

        String name = categoryPageQueryDTO.getName();
        Integer type=categoryPageQueryDTO.getType();
        Page<Category> categoryPage = categoryService.lambdaQuery()
                .like(StrUtil.isNotBlank(name), Category::getName, name)
                .eq(type != null, Category::getType, type)
                .page(page);
        return Result.success(new PageResult(categoryPage.getTotal(), categoryPage.getRecords()));
    }
    @GetMapping
    public List<Category> getByIds(@RequestParam("ids") List<Long> ids) {
        List<Category> categories = categoryService.listByIds(ids);
//        List<String> names = categories.stream().map(Category::getName).collect(Collectors.toList());
        return categories;
    }
}
